#include <SFML\Graphics.hpp>
#include <SFML\Window.hpp>
#include "ViewManager.h"
#include "Avatar.h"
#include "World.h"
#include <iostream>
using namespace std;
using namespace sf;
int main()
{
	//creates the window
	RenderWindow window= RenderWindow(VideoMode(600, 600), "First iteration programm");
	window.clear(Color(255, 255, 255, 255));

	//creates the avatar
	Avatar avatar(20,20,Color::Blue, Vector2f(0,0),0,-50);
	//creates the world
	World world;
	world.init();
	
	float mUpdateRate(1.0f / 20); // Compute Game Logic to run at 20 Hz.  You can change this to 15, 30, or some other rate you desire.
	// Clock used in restricting Update loop to a fixed rate
    sf::Clock begin;
	// Clock used in calculating the time elapsed since the last frame
    //sf::Clock anFrameClock;
    // Restart/Reset our Update clock
    begin.restart();
	// When do we need to update next (in milliseconds)?
    sf::Int32 anUpdateNext = begin.getElapsedTime().asMilliseconds();

	// Reduce CPU usage by limiting the times a frame
    // is drawn per second
    window.setFramerateLimit(30);

	//creates the ViewManager
	ViewManager myCamera(avatar.getForm(), window, 150);
	myCamera.center_view();

	float gravity=980;
	bool collides=false;
	 while (window.isOpen())
    {
		// When do we need to update next (in milliseconds)?
		float delta=begin.restart().asSeconds();
		avatar.setVelocity(Vector2f(0,0));
		if (!collides) {avatar.setVelocity(Vector2f(0,gravity));}
		sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
			
			if (sf::Keyboard::isKeyPressed(Keyboard::Left)) {avatar.addVelocity(Vector2f(-100,0)); myCamera.follow_target();}
			if (sf::Keyboard::isKeyPressed(Keyboard::Right)) {avatar.addVelocity(Vector2f(100,0)); myCamera.follow_target();}
			if (sf::Keyboard::isKeyPressed(Keyboard::Down)) {avatar.addVelocity(Vector2f(0,300)); myCamera.follow_target();}
			if (sf::Keyboard::isKeyPressed(Keyboard::Space)) {avatar.addVelocity(Vector2f(0,-300));}
        }
		avatar.move(delta);
		if(world.collides(avatar.getForm())){avatar.move(-delta); collides=true;}
		else {collides=false;}

		window.clear(Color(255, 255, 255, 255));
		world.draw(window);
	
		avatar.draw(window);
		window.setView(myCamera.getView());
        window.display();
		//make sure of the current update time

		sf::Int32 current = begin.getElapsedTime().asMilliseconds();
		// Process our UpdateFixed portion of the game loop
		while(current< mUpdateRate*1000)
		{
		current=begin.getElapsedTime().asMilliseconds();
		}
		cout<<current<<endl;
		
		
    }


return 0;
}